package com.tuo51.childcare.controller;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.tuo51.childcare.service.impl.MPPaymentService;
import com.tuo51.evaluate.service.EvaluateV2Service;
import com.tuo51.core.service.StaffService;
import com.tuo51.evaluate.service.appuser.PaymentService;
import com.tuo51.foudation.model.APPErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

import static com.tuo51.foudation.constant.APPConstants.PARENT_PAY_REPORT_PRODUCT_ID;
import static org.springframework.web.bind.annotation.RequestMethod.GET;


@RestController
@Slf4j
@RequestMapping("/papi/pay")
@Api(value = "/papi/pay", tags = "家长服务号 - 支付")
public class PAPIPayController {

    @Autowired
    MemVerificationCache cache;

    @Autowired
    StaffService staffService;

    @Autowired
    EvaluateV2Service evaluateV2Service;

    @Autowired
    MPPaymentService mpPaymentService;

    @Autowired
    PaymentService paymentService;

    @RequestMapping(value = "/order_list", method = GET)
    public StatusResponse orderList(@RequestHeader("ticket") String ticket ) {

        String userId = cache.getStaffId(ticket);

        List payOrder = paymentService.getAllOrdersForUser(userId);

        return StatusResponse.success(payOrder);
    }

    @RequestMapping(value = "/pay_report_order", method = GET, produces = "application/json")
    public StatusResponse wxOrder(@RequestHeader("ticket") String ticket,
                                  @RequestParam("reportId") String reportId,
                                  @RequestParam(value = "promoCode", required = false) String promoCode) {

        String userId = cache.getStaffId(ticket);

        Map<String,Object> result ;

        try {
            result = mpPaymentService.createWxReportOrder(userId, PARENT_PAY_REPORT_PRODUCT_ID, reportId, promoCode);
        } catch (WxPayException e) {
            log.error("微信支付异常:", e);
            return StatusResponse.error(APPErrorCode.CREATE_PAY_ORDER_FAIL.getCode(),e.getReturnMsg());
        } catch (JSONException e) {
            log.error("预料之外的异常:", e);
            return StatusResponse.error(APPErrorCode.CREATE_PAY_ORDER_FAIL.getCode(),e.getLocalizedMessage());
        }
        return StatusResponse.success(result);
    }

}
